import 'dart:async';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_is_know_dialog.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

/// 创建分类
class CreateSmartHomeCategoryPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "CreateSmartHomeCategoryPage";
  //门店id
  final String shid;
  final String stid;
  //标题
  final String title;
  final int imageCount;
  //当前创建的分组所在的排序
  final int order;

  const CreateSmartHomeCategoryPage(
      {Key key, this.shid, this.title, this.stid, this.order, this.imageCount}) : super(key:key);

  @override
  _CreateSmartHomeCategoryPageState createState() => _CreateSmartHomeCategoryPageState();

  static Future<dynamic> navigatorPush(BuildContext context, String shid,
   String title, int imageCount, int order, {String stid}){
    return RouterUtils.routeForFutureResult(
        context,
        CreateSmartHomeCategoryPage(
          shid: shid,
          title: title,
          imageCount: imageCount,
          order: order,
          stid: stid,
        ),
        routeName: CreateSmartHomeCategoryPage.ROUTER
    );
  }
}

class _CreateSmartHomeCategoryPageState
    extends BaseState<CreateSmartHomeCategoryPage> {

  TextEditingController _titleController;
  SmartHomeViewModel _viewModel;
  //指示牌标题
  String _title = "";
  String _originTitle = "";

  @override
  void initState() {
    super.initState();
    _viewModel = SmartHomeViewModel(this);
    _title = widget?.title;
    if(StringUtils.isNotEmpty(_title)){
      _title = widget?.title;
      _originTitle = _title;
      _titleController = TextEditingController(text: _title);
      Future.delayed(Duration(milliseconds: 500))
          .then((value) {
        _titleController.selection=TextSelection.fromPosition(TextPosition(
            affinity: TextAffinity.downstream,
            offset: _titleController.text.length));
      }
      );
    }else{
      _titleController = TextEditingController();
    }
  }

  @override
  void dispose() {
    _titleController.clear();
    _titleController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Color(0xFFF6F7F9),
          body: _toMainColumnWidget(),
        )
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: [
        _toTopBarWidget(),
        _toSmartHomeTitleWidget(),
      ],
    );
  }

  ///页面标题
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "分类",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: _toSaveButtonWidget(),
    );
  }

  Widget _toSaveButtonWidget() {
    return Row(
      children: [
        Visibility(
          visible: StringUtils.isNotEmpty(_originTitle),
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: ()async{
              if((widget?.imageCount??0) > 0){
                CommonISeeDialog.navigatorPushDialog(context,
                    content: "该分类下已有文件，不允许删除",
                  confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                  titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                  contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                  widgetBgColor: Colors.white,
                );
                return;
              }
              bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
                title: "提示",
                content: "确认删除当前分类(${widget?.title})？",
                cancelText: "取消",
                confirmText: "确认",
                confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                cancelBgColor: Color(0xFFF6F7F9),
                titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                widgetBgColor: Colors.white,
              );
              if (result ?? false) {
                _viewModel.deleteCategory(context, widget?.shid, widget?.stid, widget?.order);
              }
            },
            child: Container(
              height: 44,
              padding: EdgeInsets.symmetric(horizontal: 22),
              alignment: Alignment.center,
              child: Text(
                "删除",
                style: TextStyle(
                  fontSize: 12,
                  color: Color(0xFF8B93A5),
                ),
              ),
            ),
          ),
        ),
        CommonFixedHeightConfirmButtonWidget(
          isAlive: isCanSave(),
          width: 48,
          height: 24,
          unSelectBgColor:Color(0xFFCFD4DB),
          selectedBgColor:
          ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          unSelectTextStyle: TextStyle(
              color: Colors.white,
              fontSize: 12,
              fontWeight: FontWeight.w600),
          selectedTextStyle: TextStyle(
              color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
          text: "保存",
          onTap: (){
            _save();
          },
        ),
      ],
    );
  }

  void _save(){
    if(StringUtils.isNotEmpty(widget?.stid??"")){
      //编辑
      _viewModel.editCategory(context, _title.trim(), widget?.shid, widget?.stid, widget?.order);
    }else{
      //新增
      _viewModel.createCategory(context, _title.trim(), widget?.shid, widget?.order);
    }
  }

  ///指示牌标题
  Widget _toSmartHomeTitleWidget(){
    return Container(
      height: 50,
      color: Colors.white,
      child: Container(
        height: 50,
        padding: EdgeInsets.symmetric(horizontal: 15),
        child: Container(
          alignment: Alignment.centerLeft,
          child: VgTextField(
            controller: _titleController,
            keyboardType: TextInputType.text,
            autofocus: true,
            style: TextStyle(
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                fontSize: 14),
            decoration: new InputDecoration(
                counterText: "",
                hintText: "输入分类名称",
                border: InputBorder.none,
                hintStyle: TextStyle(
                    fontSize: 14,
                    color: Color(0XFFB0B3BF))),
            inputFormatters: <TextInputFormatter> [
              LengthLimitingTextInputFormatter(6)
            ],
            maxLines: 1,
            onChanged: (value){
              _notifyChange();
            },
          ),
        ),
      ),
    );
  }

  ///通知更新
  _notifyChange() {
    _title = _titleController?.text?.trim();
    setState(() { });
  }

  bool isCanSave(){
    //没有内容
    if(StringUtils.isEmpty(_title)){
      return false;
    }
    //与原来内容相同
    if(_title.trim() == _originTitle.trim()){
      return false;
    }
    return true;
  }


}
